<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加设备"
    width="80%"
    :close-on-click-modal="false"
    :before-close="rest"
  >
    <!-- 添加设备 表单 -->
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="top">
      <el-row :gutter="28">
        <!-- 设备名称 -->
        <el-col :span="12">
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="ruleForm.name" clearable />
          </el-form-item>
        </el-col>
        <!-- 设备类型 级联选择器 -->
        <el-col :span="12">
          <el-form-item label="设备类型" prop="TaskGroupValue">
            <el-cascader
              style="width: 100%"
              v-model="selectList"
              :options="options"
              @change="selectChange(selectList)"
              :show-all-levels="false"
              placeholder="请选择设备类型"
              :props="{ value: 'DevicetypeValue', label: 'DevicetypeName', checkStrictly: true }"
            />
          </el-form-item>
        </el-col>
        <!-- 新增其它设备 -->
        <template v-if="Showdevice">
          <!-- 上面设备名称 设备类型 -->
          <el-col>
            <div style="margin: 2% 0; font-size: 18px; font-weight: 600">系统参数</div>
          </el-col>
          <el-col>
            <el-form-item label="IO模块">
              <el-select
                v-model="IOmodelValue"
                style="width: 100%"
                @change="IOmodelchange"
                placeholder="请选择IO模块"
              >
                <el-option
                  v-for="(item, index) in IOmodelList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 下面针脚对应关系 -->
          <el-col>
            <el-table :data="otherDeviceValue.pins" style="width: 100%" show-overflow-tooltip>
              <el-table-column label="传感器引脚" align="center">
                <template #default="scope">
                  <span>{{ scope.row.name }}</span>
                </template>
              </el-table-column>
              <!-- <input type="hidden" name="scope.row.statusval" /> -->
              <el-table-column label="名称" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.statusName"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="模块引脚" align="center">
                <template #default="scope">
                  <!-- 输出引脚 -->
                  <span v-if="scope.row.type === 'COUNTER_TYPE_OUTPUT'">
                    <el-select
                      v-model="scope.row.channel"
                      placeholder="请选择输出模块的引脚"
                      clearable
                    >
                      <el-option
                        v-for="(item, index) in outputChannels"
                        :key="index"
                        :label="item.name"
                        :value="item.value"
                        :disabled="item.disabled"
                      />
                    </el-select>
                  </span>
                  <!-- 输入引脚 -->
                  <span v-else>
                    <el-select
                      v-model="scope.row.channel"
                      placeholder="请选择输入模块的引脚"
                      clearable
                    >
                      <el-option
                        v-for="(item, index) in inputChannels"
                        :key="index"
                        :label="item.name"
                        :value="item.value"
                        :disabled="item.disabled"
                      />
                    </el-select>
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </template>
        <!-- 新增杰控8通道 -->
        <template v-else-if="Showeigth">
          <el-col
            ><div style="margin: 2% 0; font-size: 18px; font-weight: 600">系统参数</div></el-col
          >
          <el-col :span="12">
            <el-form-item label="485地址">
              <el-input placeholder="485地址请填1" v-model="ruleForm.dvcActualId"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通讯波特率">
              <el-select
                v-model="ruleForm.BaudRate"
                style="width: 100%"
                placeholder="请选择通讯波特率"
              >
                <el-option
                  v-for="(item, index) in BaudRate"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请选择设备接入的COM口">
              <el-select
                v-model="ruleForm.ComPort"
                placeholder="请选择COM"
                style="flex: 1; width: 100%"
                clearable
              >
                <el-option
                  v-for="item in comList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请输入设备的通道数">
              <el-select
                v-model="ChannelsDevice"
                placeholder="请选择"
                style="flex: 1; width: 100%"
                clearable
                @change="ChannelsDeviceChange"
              >
                <el-option
                  v-for="item in ChannelList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <!-- 新增传感器 -->
        <template v-else-if="ruleForm.sensorType === 'sensor'">
          <el-col
            ><div style="margin: 2% 0; font-size: 18px; font-weight: 600">
              {{ propertyValue.DevicetypeName }}
            </div></el-col
          >
          <el-col>
            <el-form-item label="485地址">
              <el-input
                placeholder="485地址不能大于255"
                v-model="ruleForm.dvcActualId"
                type="number"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通讯波特率">
              <el-select
                v-model="ruleForm.BaudRate"
                style="width: 100%"
                placeholder="请选择通讯波特率"
              >
                <el-option
                  v-for="(item, index) in BaudRate"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="请选择设备接入的COM口">
              <el-select
                v-model="ruleForm.ComPort"
                placeholder="请选择COM"
                style="flex: 1; width: 100%"
                clearable
              >
                <el-option
                  v-for="item in comList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-for="(item, index) in propertyValue.property" :key="index">
            <el-form-item :label="item.propertyName">
              <el-input
                :placeholder="`请输入${item.name}`"
                v-model="item.statusName"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </template>
        <!-- 寄存器 -->
        <template v-else-if="ruleForm.sensorType === 'Register'">
          <el-col
            ><div style="margin: 2% 0; font-size: 18px; font-weight: 600">
              {{ propertyValue.DevicetypeName }}
            </div></el-col
          >
          <el-col>
            <el-form-item label="485地址">
              <el-input
                placeholder="485地址不能大于255"
                v-model="ruleForm.dvcActualId"
                type="number"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通讯波特率">
              <el-select
                v-model="ruleForm.BaudRate"
                style="width: 100%"
                placeholder="请选择通讯波特率"
              >
                <el-option
                  v-for="(item, index) in BaudRate"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="请选择设备接入的COM口">
              <el-select
                v-model="ruleForm.ComPort"
                placeholder="请选择COM"
                style="flex: 1; width: 100%"
                clearable
              >
                <el-option
                  v-for="item in comList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-for="(item, index) in propertyValue.property" :key="index">
            <el-form-item :label="item.propertyName">
              <el-input
                v-if="item.type === 'write'"
                :placeholder="item.propertyName"
                v-model="item.statusName"
                disabled
              ></el-input>
              <el-input v-else v-model="item.value" placeholder="单位为毫秒"> </el-input>
            </el-form-item>
          </el-col>
        </template>
        <!-- 特殊设备 -->
        <template v-else-if="ruleForm.sensorType === 'SpecialEquipment'">
          <el-col
            ><div style="margin: 2% 0; font-size: 18px; font-weight: 600">
              {{ propertyValue.DevicetypeName }}
            </div></el-col
          >
          <el-col>
            <el-form-item label="485地址">
              <el-input
                placeholder="485地址不能大于255"
                v-model="ruleForm.dvcActualId"
                type="number"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通讯波特率">
              <el-select
                v-model="ruleForm.BaudRate"
                style="width: 100%"
                placeholder="请选择通讯波特率"
              >
                <el-option
                  v-for="(item, index) in BaudRate"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="请选择设备接入的COM口">
              <el-select
                v-model="ruleForm.ComPort"
                placeholder="请选择COM"
                style="flex: 1; width: 100%"
                clearable
              >
                <el-option
                  v-for="item in comList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-for="(item, index) in propertyValue.property" :key="index">
            <el-form-item :label="item.propertyName">
              <el-input
                v-if="item.type === 'write'"
                :placeholder="item.propertyName"
                v-model="item.statusName"
                disabled
              ></el-input>
              <el-input v-else v-model="item.value" placeholder="单位为毫秒"> </el-input>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="danger" @click="close"> 取消 </el-button>
        <el-button type="primary" @click="submit"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import MyJson from '../../MyJson/DeviceProperties.json'
import until from '../../until/csUntil/deviceUtils.js'
import { v4 as uuidv4 } from 'uuid'
import { ElMessage } from 'element-plus'
import ChannelLists from './Channels.json'
export default {
  setup(_, { emit }) {
    // 在组件挂载后获取串口列表
    onMounted(() => {
      getComAll()

      const deviceTypeStr = store.state.deviceTypeStr
      const device = JSON.parse(JSON.stringify(deviceTypeStr))
      const filterVirtual = device.children.filter((item) => item.isVirtual === 'IS_NOT_VIRTUAL')

      filterVirtual.forEach((element) => {
        if (element.Channels) {
          element.DevicetypeValue = uuidv4()
        }
      })
      device.children = filterVirtual
      options.value = [device]
    })
    const ChannelList = ref(ChannelLists)
    // 获取到的COM
    const comList = ref([])
    // vuex 实例对象
    const store = useStore()
    // dialog 显示隐藏
    const dialogVisible = ref(false)
    // 设备类型
    const options = ref(null)
    // 设备 列表
    const deviceList = ref(store.state.beforeAllDevice)
    // 通讯波特率
    const BaudRate = ref(MyJson.template[0])
    // dialog 表单
    const ruleForm = ref({
      id: '',
      pid: '',
      name: '',
      Channels: -1,
      DevicetypeName: '',
      DevicetypeValue: null,
      isShow: '1',
      amplitude: '0',
      delay: '1',
      BaudRate: 9600,
      property: [],
      pins: [],
      version: '3.0',
      type: '485',
      dvcActualId: '',
      isVirtual: 'IS_NOT_VIRTUAL',
      ComPort: '',
      DeviceVariable: 'UNAVAILABLE',
      sensorType: ''
    })
    // dialog 检验规则
    const rules = reactive({
      name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }]
    })
    // 级联选择器选中的值
    const selectList = ref(null)
    // select 级联选择器 选中的值
    const selectValue = ref(null)
    // 8通道设备添加
    const Showeigth = ref(null)
    // 环境传感器 切换
    const Sensor = ref(false)
    // 新增 设备切换
    const Showdevice = ref(false)
    // IO模块的List
    const IOmodelList = ref(null)
    // IO模块选择的值
    const IOmodelValue = ref(null)
    // 环境传感器 筛选的值
    const propertyValue = ref(null)
    // 其它设备 筛选的值
    const otherDeviceValue = ref([])
    // 输入通道的值
    const inputChannels = ref([])
    // 输出通道的值
    const outputChannels = ref([])
    // 表单实例对象
    const ruleFormRef = ref(null)
    // 虚拟设备显示隐藏
    const Virtual = ref(false)
    // 虚拟设备 筛选的值
    const VirtualValue = ref(null)

    const ChannelsDevice = ref()
    // 设备类型 select  change 事件
    const selectChange = (data) => {
      ruleForm.value.BaudRate = 9600
      getComAll()
      selectValue.value = data[data.length - 1]
      ruleForm.value.DevicetypeValue = data[data.length - 1]
      const res = until.findDeviceByValue(options.value, ruleForm.value.DevicetypeValue)
      // console.log(res)
      ruleForm.value.sensorType = res.sensorType
      IOmodelValue.value = null
      propertyValue.value = null
      otherDeviceValue.value = null
      VirtualValue.value = null
      inputChannels.value = []
      outputChannels.value = []
      // let checkvalue = ''
      // options.value.forEach((item) => {
      //   item.children.forEach((e) => {
      //     if (e.DevicetypeValue === data[1]) {
      //       checkvalue = e.Channels
      //     }
      //   })
      // })
      // 杰控 8通道
      // console.log(!data[2], ruleForm.value.DevicetypeValue)
      if (ruleForm.value.DevicetypeValue === 2001) {
        // 关闭虚拟设备
        Virtual.value = false
        // 关闭 环境传感器
        // 关闭 设备
        Showdevice.value = false
        // 打开 8通道设备
        Showeigth.value = true
        const res = until.findDeviceByValue(options.value, ruleForm.value.DevicetypeValue)
        const result = Object.assign({}, res)
        delete result.children
        ruleForm.value.pins = []
        ruleForm.value.property = []
        ruleForm.value.id = uuidv4()

        ruleForm.value.DevicetypeName = result.DevicetypeName

        const deviceTypeStr = store.state.deviceTypeStr
        const device = JSON.parse(JSON.stringify(deviceTypeStr))
        let dddsss = null
        device.children.forEach((item) => {
          if (item.DevicetypeName === ruleForm.value.DevicetypeName) {
            dddsss = item.DevicetypeValue
          }
        })

        ruleForm.value.DevicetypeValue = dddsss
        ruleForm.value.isShow = result.isShow
        ruleForm.value.pid = '-1'
        ruleForm.value.isVirtual = 'IS_NOT_VIRTUAL'
        ruleForm.value.ComPort = ''
        ruleForm.value.DeviceVariable = 'UNAVAILABLE'
      }
      // 环境传感器
      else if (ruleForm.value.sensorType === 'sensor') {
        Virtual.value = false
        Showdevice.value = false
        Showeigth.value = false
        const res = until.findDeviceByValue(options.value, ruleForm.value.DevicetypeValue)
        propertyValue.value = JSON.parse(JSON.stringify(res))
        ruleForm.value.id = uuidv4()
        ruleForm.value.pins = []
        ruleForm.value.property = propertyValue.value.property
        ruleForm.value.Channels = -1
        ruleForm.value.dvcActualId = ''
        ruleForm.value.isShow = propertyValue.value.isShow
        ruleForm.value.DevicetypeName = propertyValue.value.DevicetypeName
        ruleForm.value.DevicetypeValue = propertyValue.value.DevicetypeValue
        ruleForm.value.pid = '-1'
        ruleForm.value.isVirtual = 'IS_NOT_VIRTUAL'
        ruleForm.value.ComPort = ''
        ruleForm.value.DeviceVariable = 'AVAILABLE'
      }
      // 寄存器
      else if (
        ruleForm.value.sensorType === 'Register' ||
        ruleForm.value.sensorType === 'SpecialEquipment'
      ) {
        Virtual.value = false
        Showdevice.value = false
        Showeigth.value = false
        const res = until.findDeviceByValue(options.value, ruleForm.value.DevicetypeValue)
        propertyValue.value = JSON.parse(JSON.stringify(res))
        ruleForm.value.id = uuidv4()
        ruleForm.value.pins = []
        ruleForm.value.property = propertyValue.value.property
        ruleForm.value.Channels = -1
        ruleForm.value.dvcActualId = ''
        ruleForm.value.isShow = 'write'
        ruleForm.value.DevicetypeName = propertyValue.value.DevicetypeName
        ruleForm.value.DevicetypeValue = propertyValue.value.DevicetypeValue
        ruleForm.value.pid = '-1'
        ruleForm.value.isVirtual = 'IS_NOT_VIRTUAL'
        ruleForm.value.ComPort = propertyValue.value.ComPort
        ruleForm.value.DeviceVariable = 'UNAVAILABLE'
      }
      // 其它设备
      else {
        Virtual.value = false
        Showeigth.value = false
        Showdevice.value = true
        const listDvcAndDvcVer = window.api.listDvcAndDvcVer()
        store.commit('beforeAllDeviceupdate', JSON.parse(listDvcAndDvcVer))
        const devicetypeList = JSON.parse(listDvcAndDvcVer)
        const res = devicetypeList.filter(
          (item) =>
            (item.DevicetypeValue === 2001 || item.DevicetypeValue === 2008) && item.isDelete === 0
        )
        res === -1 ? (IOmodelList.value = []) : (IOmodelList.value = res)
        const result = until.findDeviceByValue(options.value, ruleForm.value.DevicetypeValue)
        otherDeviceValue.value = JSON.parse(JSON.stringify(result))
        ruleForm.value.id = uuidv4()
        ruleForm.value.pins = otherDeviceValue.value.pins
        ruleForm.value.property = otherDeviceValue.value.property
        ruleForm.value.isShow = otherDeviceValue.value.isShow
        ruleForm.value.DevicetypeName = otherDeviceValue.value.DevicetypeName
        ruleForm.value.DevicetypeValue = otherDeviceValue.value.DevicetypeValue
        ruleForm.value.isVirtual = 'IS_NOT_VIRTUAL'
        ruleForm.value.ComPort = ''
        ruleForm.value.DeviceVariable = 'UNAVAILABLE'
      }
    }

    // IO模块 change事件
    const IOmodelchange = () => {
      const deviceall = store.state.beforeAllDevice
      const deviceOutput = []
      const deviceInput = []
      deviceall.map((item) => {
        if (item.pins.length) {
          if (item.pid === IOmodelValue.value) {
            item.pins.map((pin) => {
              if (pin.type === 'COUNTER_TYPE_INPUT') {
                deviceInput.push(pin.channel)
              }
              if (pin.type === 'COUNTER_TYPE_OUTPUT') {
                deviceOutput.push(pin.channel)
              }
            })
          }
        }
      })
      inputChannels.value = []
      outputChannels.value = []
      const IoList = IOmodelList.value.filter((item) => item.id === IOmodelValue.value)
      ruleForm.value.BaudRate = IoList[0].BaudRate
      ruleForm.value.dvcActualId = IoList[0].dvcActualId
      ruleForm.value.pid = IoList[0].id
      for (let i = 0; i < IoList[0].Channels; i++) {
        inputChannels.value.push({ name: `输入通道${i + 1}`, value: `${i}` })
        outputChannels.value.push({ name: `输出通道${i + 1}`, value: `${i}` })
      }
      if (ruleForm.value.DevicetypeValue != 2001 || ruleForm.value.DevicetypeValue != 2002) {
        ruleForm.value.Channels = IoList[0].Channels
      }
      // deviceallList.forEach((item, index) => {
      //  if(item.)
      // })
      const inputresult = inputChannels.value.map((item) => {
        if (deviceInput.includes(item.value)) {
          return { ...item, disabled: true }
        } else {
          return item
        }
      })

      const Outputresult = outputChannels.value.map((item) => {
        if (deviceOutput.includes(item.value)) {
          return { ...item, disabled: true }
        } else {
          return item
        }
      })

      inputChannels.value = inputresult
      outputChannels.value = Outputresult
    }

    const ChannelsDeviceChange = () => {
      ruleForm.value.Channels = ChannelsDevice.value
      // console.log(ruleForm.value.Channels, ChannelsDevice.value)
    }
    // 提交表单
    const submit = async () => {
      // console.log(ruleForm.value, ChannelList.value)
      ruleFormRef.value.validate((validate) => {
        if (validate) {
          // 杰控8通道
          const insertDvcAndDvcVersion = window.api.insertDvcAndDvcVersion(
            JSON.stringify(ruleForm.value)
          )
          if (insertDvcAndDvcVersion === '新增成功') {
            ElMessage.success('新增成功')
            rest()
            dialogVisible.value = false
            emit('update')
          } else {
            ElMessage.error(insertDvcAndDvcVersion)
          }
        }
      })
    }

    const rest = () => {
      selectList.value = null
      Sensor.value = false
      Showeigth.value = false
      Showdevice.value = false
      Virtual.value = false
      ruleForm.value.TaskGroupValue = []
      VirtualValue.value = null
      otherDeviceValue.value = null
      ruleForm.value.name = ''
      ruleForm.value.dvcActualId = ''
      dialogVisible.value = false
      ruleForm.value.BaudRate = 9600
      propertyValue.value = []
      ruleForm.value.sensorType = ''
    }

    // 拿到所有的COM接口
    const getComAll = async () => {
      try {
        const res = await window.api.getCOM()
        comList.value = res.map((item) => {
          return {
            label: item.path,
            value: item.path
          }
        })
      } catch (error) {
        console.error('Error fetching COM list:', error)
      }
    }

    // 测试按钮
    const dds = () => {}

    const close = () => {
      selectList.value = null
      Sensor.value = false
      Showeigth.value = false
      Showdevice.value = false
      Virtual.value = false
      ruleForm.value.TaskGroupValue = []
      ruleForm.value.sensorType = ''
      VirtualValue.value = null
      otherDeviceValue.value = null
      ruleForm.value.name = ''
      ruleForm.value.dvcActualId = ''
      dialogVisible.value = false
      ruleForm.value.BaudRate = 9600
      propertyValue.value = []
    }
    // // 是
    // const Comconfirm = async () => {
    //   submit()
    //   const BR = JSON.parse(JSON.stringify(ruleForm.value.BaudRate))
    //   const Com = JSON.parse(JSON.stringify(ruleForm.value.ComPort))
    //   const res = await window.api.openCom(Com, JSON.stringify(BR))
    //   if (res === '打开串口成功') {
    //     ElMessage.success(res)
    //   } else {
    //     ElMessage.error('打开串口失败')
    //   }
    // }
    // // 否
    // const Comcancel = () => {
    //   submit()
    // }
    return {
      Showdevice,
      dialogVisible,
      options,
      ruleForm,
      rules,
      BaudRate,
      deviceList,
      Showdevice,
      Showeigth,
      Sensor,
      IOmodelValue,
      IOmodelList,
      propertyValue,
      inputChannels,
      outputChannels,
      otherDeviceValue,
      selectList,
      ruleFormRef,
      Virtual,
      VirtualValue,
      comList,
      ChannelsDevice,
      ChannelList,
      ChannelsDeviceChange,
      dds,
      selectChange,
      IOmodelchange,
      submit,
      rest,
      close
    }
  }
}
</script>

<style>
</style>